package com.liveinstars.xxl.config;

import com.xxl.job.core.executor.impl.XxlJobSpringExecutor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
import org.springframework.boot.actuate.endpoint.annotation.WriteOperation;
import org.springframework.context.annotation.Configuration;

import java.util.Collections;
import java.util.Map;

/**
 * Created by wangxj on 2019/04/23.
 */
/*
 * shell脚本的项目平滑关闭时访问
 * actuator的shutdown不会关闭其他server启的进程，必须手动添加相应的endpoint
 */
@Configuration
@Endpoint(id = "onepiece-shutdown")
public class XxlJobShutDownEndPoint {
    private static final Map<String, String> NO_CONTEXT_MESSAGE = Collections.unmodifiableMap(Collections.singletonMap("message", "No context to shutdown."));
    private static final Map<String, String> SHUTDOWN_MESSAGE = Collections.unmodifiableMap(Collections.singletonMap("message", "Shutting down, bye..."));

    @Autowired
    private XxlJobSpringExecutor xxlJobSpringExecutor;

    @WriteOperation
    public Map<String, String> shutdown() {
        if (xxlJobSpringExecutor == null) {
            return NO_CONTEXT_MESSAGE;
        } else {
            xxlJobSpringExecutor.destroy();
            return SHUTDOWN_MESSAGE;
        }
    }
}
